package com.javaDemo.node.node2;

/**
 * @ClassName: Fanzhuannode
 * @Auther: csy
 * @Date: 2020/11/12 20:36
 * @Description:
 */
public class Fanzhuannode {

    public static void main(String[] args) {
        Node result=new Node();
        Node result2=new Node();
        Node node=new Node(1);
        Node node2=new Node(2);
        Node node3=new Node(3);
        Node node4=new Node(4);

        node.next=node2;
        node2.next=node3;
        node3.next=node4;
        // result=reverseListByInsert(node);
        result2=reverseListByLocal(node);
        System.out.println(result);
        System.out.println(result2);
    }

    /**
     * 头插反转
     * @param node
     * @return
     */
    public static Node reverseListByInsert(Node node){
        //定义一个带头节点的
        Node resultList = new Node(-1);
        //循环节点
        Node p = node;
        while(p!= null){
            //保存插入点之后的数据
            Node tempList = p.next;
            p.next = resultList.next;
            resultList.next = p;
            p = tempList;
        }
        return resultList.next;
    }

    /**
     * 就地反转
     * @param node
     * @return
     */
    public static Node reverseListByLocal(Node node){
        Node resultList = new Node(-1);
        resultList.next= node;
        Node p = node;
        Node pNext = p.next;
        while (pNext!=null){
            p.next = pNext.next;
            pNext.next = resultList.next;
            resultList.next = pNext;
            pNext=p.next;
        }
        return resultList.next;
    }
}
